package com.qyer.lxp.common.framework.httpclient;

import com.qyer.lxp.common.framework.contants.QyerContants;
import com.qyer.lxp.common.framework.util.QyerConfig;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.log4j.Logger;

/**
 * Created by jiangping on 16/5/16.
 */
public class HttpClientPoolCache {

    protected static final Logger logger = Logger.getLogger(HttpClientUtil.class);

    private static PoolingClientConnectionManager pccm = null;

    private HttpClientPoolCache() {
    }

    private static class HttpClientPoolCacheHolder{
        private static final HttpClientPoolCache instance = new HttpClientPoolCache();
    }

    public static final HttpClientPoolCache getInstance() {
        return HttpClientPoolCacheHolder.instance;
    }

    public HttpClient getHttpClient()
    {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80,PlainSocketFactory.getSocketFactory()));

        pccm = new PoolingClientConnectionManager(schemeRegistry);
        try
        {
            pccm.setMaxTotal(QyerConfig.getInstance().getInt(QyerContants.QYER_CONNECTION_MAX_TOTAL, 500));
        } catch (NumberFormatException e)
        {
            logger.error("Key[httpclient.max_total] Not Found in systemConfig.properties", e);
        }
        // 每条通道的并发连接数设置（连接池）
        try
        {
            pccm.setDefaultMaxPerRoute(QyerConfig.getInstance().getInt(QyerContants.QYER_CONNECTION_PER_ROUTE_MAX_TOTAL, 2000));
        } catch (NumberFormatException e)
        {
            logger.error("Key[httpclient.default_max_connection] Not Found in systemConfig.properties", e);
        }
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, QyerConfig.getInstance().getInt(QyerContants.QYER_CONNECTION_TIME_OUT, 5000)); // 5000ms
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, QyerConfig.getInstance().getInt(QyerContants.QYER_CONNECTION_TIME_OUT, 5000));
        params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "utf-8");
        params.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "utf-8");
        return new DefaultHttpClient(pccm, params);
    }
}
